package br.org.group.android.gui;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;
import br.org.group.android.app.ConfigurationVO;
import br.org.group.android.app.FortuneProvider;
import br.org.group.android.app.FortuneVO;
import br.org.group.android.app.R;
import br.org.group.android.dao.FortunesDbAdapter;
import br.org.group.android.utils.FortuneProviderUtils;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

/**
 * Created by IntelliJ IDEA. User: abner Date: 1/12/11 Time: 10:56 PM 26/01/2011
 * - Victor Henrique Fugiwara Adicionada a opcão de compartilhar a Fortune
 * através de uma opcão no menu.
 *  - Júlio Cotta - Correções diversas e configurador Date:26/06/2011
 */

public class FortunesActivity extends SherlockActivity {

	private static final int SHARE_FORTUNE = Menu.FIRST;
	private static final int CONFIGURE_FORTUNE = SHARE_FORTUNE + 1;
	private static final int ABOUT_FORTUNE = SHARE_FORTUNE + 2;
	private static final String APP_NAME = "Froid";
	private FortuneVO fortune;
	private FortuneProvider provider;
	private ConfigurationVO c;
	private Dialog dialog;
	private CheckBox cbSaveDefault;
	private RadioButton rbShareLink;
	private RadioButton rbShareMsg;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fortunes_activity);

		c = (new FortunesDbAdapter(this)).getConfiguration(ConfigurationVO.CONFIG_SHARE);
		fortune = new FortuneVO();

		Intent intent = getIntent();
		Bundle extras = intent.getExtras(); 
		if (extras != null) {

			fortune.setId(extras.getInt(FortunesWidget.FORTUNE_ID, 0));
			fortune.setAutor(extras.getString(FortunesWidget.FORTUNE_AUTOR));
			fortune.setMensagem(extras.getString(FortunesWidget.FORTUNE_MSG));

		}else if(savedInstanceState != null){
			fortune.setId((Integer)savedInstanceState.getSerializable(FortunesWidget.FORTUNE_ID));
			fortune.setAutor((String)savedInstanceState.getSerializable(FortunesWidget.FORTUNE_AUTOR));
			fortune.setMensagem((String)savedInstanceState.getSerializable(FortunesWidget.FORTUNE_MSG));

		}
		
		fillFortune();

	}

	@SuppressLint("NewApi")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		supportInvalidateOptionsMenu();
		refreshWidget();
	}
	
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(FortunesWidget.FORTUNE_ID, fortune.getId());
		outState.putSerializable(FortunesWidget.FORTUNE_AUTOR,fortune.getAutor());
		outState.putSerializable(FortunesWidget.FORTUNE_MSG,fortune.getMensagem());
    }

	@Override
	public void onResume() {
		super.onResume();
		c = (new FortunesDbAdapter(this)).getConfiguration(ConfigurationVO.CONFIG_SHARE);
		fillFortune();
	}

	private void fillFortune() {
		provider = FortuneProviderUtils.getInstance(this);
		if (fortune.getId() > 0) {

			// fortune = provider.getFortune(fortuneID);
		} else {
			fortune = provider.updateFortune();
		}

		TextView txtMessage = (TextView) findViewById(R.id.txt_act_mensagem);
		txtMessage.setText(fortune.getMensagem());

		TextView txtAutor = (TextView) findViewById(R.id.txt_act_autor);
		String autor = fortune.getAutor();
		txtAutor.setText(autor.trim().length() == 0 ? "Autor desconhecido" : autor);
	}

	private void refreshWidget() {

		int[] appWidgetIds = AppWidgetManager.getInstance(this).getAppWidgetIds(new ComponentName(this,FortunesWidget.class));
		
		int N = appWidgetIds.length;

		// Faz um loop para cada App Widget que pertence a esse provider
		for (int i = 0; i < N; i++) {

			int appWidgetId = appWidgetIds[i];
			FortunesWidget.updateWidget(this,appWidgetId,fortune);

		}

	}

	private OnClickListener onClickRefresh = new OnClickListener() {

		public void onClick(View arg0) {

			fortune.setId(0);
			fillFortune();
			refreshWidget();

		}

	};

	private OnClickListener onClickShare = new OnClickListener() {
		public void onClick(View v) {
			share();
		}
	};

	private OnClickListener okListener = new OnClickListener() {

		public void onClick(View arg0) {
			if(rbShareLink.isChecked()){
				c = new ConfigurationVO(ConfigurationVO.CONFIG_SHARE,
						ConfigurationVO.SHARE_LINK);
			}
			if(rbShareMsg.isChecked()){
				c = new ConfigurationVO(ConfigurationVO.CONFIG_SHARE,
						ConfigurationVO.SHARE_MSG);
			}
			
			if (cbSaveDefault.isChecked()){
				(new FortunesDbAdapter(FortunesActivity.this)).atualizarConfiguracao(c);
			}else{
				ConfigurationVO c1 = new ConfigurationVO(ConfigurationVO.CONFIG_SHARE, ConfigurationVO.SHARE_ALWAYS_ASK);
				(new FortunesDbAdapter(FortunesActivity.this)).atualizarConfiguracao(c1);
			}
			dialog.dismiss();
			share();
		}
	};

	private void share() {
		TextView txtMessage = (TextView) findViewById(R.id.txt_act_mensagem);
		TextView txtAutor = (TextView) findViewById(R.id.txt_act_autor);

		Intent sendIntent = new Intent(Intent.ACTION_SEND);
		String mensagem = "";

		if (fortune != null) {

			switch (c.getValue()) {
			case ConfigurationVO.SHARE_ALWAYS_ASK:
				opcoesDialog();
				break;

			case ConfigurationVO.SHARE_LINK:
				mensagem = "Acesse e leia: http://fortunesweb.appspot.com/index.jsp?cls=Brazilian&id="
						+ fortune.getId() + " #Froid";
				break;

			case ConfigurationVO.SHARE_MSG:
				mensagem = fortune.getMensagem() + " #Froid";
				break;
			}

		} else {
			mensagem = "#" + APP_NAME + " " + txtMessage.getText() + " - " + txtAutor.getText();
		}
		if (c.getValue() != ConfigurationVO.SHARE_ALWAYS_ASK) {
			sendIntent.putExtra(Intent.EXTRA_SUBJECT, APP_NAME);
			sendIntent.putExtra(Intent.EXTRA_TEXT, mensagem);
			sendIntent.setType("text/plain");
			startActivity(Intent.createChooser(sendIntent, "Compartilhar via:"));
		}
	}

	private void opcoesDialog() {
		dialog = new Dialog(this);

		dialog.setContentView(R.layout.dialog_activity);
		dialog.setTitle("Opções de compartilhamento");

		rbShareLink = (RadioButton) dialog.findViewById(R.id.rb_share_link);
		rbShareMsg = (RadioButton) dialog.findViewById(R.id.rb_share_msg);
		cbSaveDefault = (CheckBox) dialog.findViewById(R.id.cb_salve);
		Button ok = (Button) dialog.findViewById(R.id.ibtn_ok);

		rbShareLink.setChecked(true);
		
		ok.setOnClickListener(okListener);
		dialog.show();

	}

	 
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		fillMenu(menu);
		return super.onPrepareOptionsMenu(menu);
	}
	public Menu fillMenu(Menu menu) {
		FortunesDbAdapter fdba = new FortunesDbAdapter(FortunesActivity.this);
		ConfigurationVO c = fdba.getConfiguration(ConfigurationVO.CONFIG_ICONS);
		if (c.getValue() == ConfigurationVO.ICONS_CLASSIC) {
			menu.getItem(0).setIcon(R.drawable.refresh_default);
			menu.getItem(1).setIcon(R.drawable.share_default);
			menu.getItem(2).setIcon(R.drawable.configure_default);
			menu.getItem(3).setIcon(R.drawable.info_default);
		} else if (c.getValue() == ConfigurationVO.ICONS_NEW) {
			menu.getItem(0).setIcon(R.drawable.refresh_teste);
			menu.getItem(1).setIcon(R.drawable.share_teste);
			menu.getItem(2).setIcon(R.drawable.configure_teste);
			menu.getItem(3).setIcon(R.drawable.info_teste);
		}
		
		return menu;
	}
		 
	/*
	 * Método que seta as acões para cada opcãoo do Menu.
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent i = null;
		
		switch (item.getItemId()) {
		case R.id.update:
			fortune.setId(0);
			fillFortune();
			refreshWidget();
			return true;
		case R.id.share:
			share();
			return true;
		case R.id.setup:
			i = new Intent(this, ConfigureActivity.class);
			startActivityForResult(i, CONFIGURE_FORTUNE);
			return true;
		case R.id.about:
			i = new Intent(this, Sobre.class);
			startActivity(i);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

}